<?php
namespace app\common\service;
use app\common\model\Upload as UploadModel;
use app\common\util\Random as RandomTool;
use app\common\util\Srt;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Exception;
use think\facade\Db;
use think\File;
use app\common\util\File as FileTool;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/12 0012
 * Time: 15:53
 */
class UploadService{

    // 存储空间名称
    private $bucket ="medical-course";

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    //$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private $endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

    private $urlHost = "https://medical-course.oss-cn-shenzhen.aliyuncs.com";

    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private $accessKeyId = "";
    private $accessKeySecret = "";

    private $ossClient;

    public function __construct()
    {
        $this->accessKeyId = env('aliyun.ali_access_key_id');
        $this->accessKeySecret = env('aliyun.ali_access_key_secret');
        $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
    }


    public function upload(File $file,$type=UploadModel::TYPE_IMAGE){

        try{

            $basePath = FileTool::createOssFilePath();
            $fileName = date("Ymd",time()).RandomTool::rand(10).".".$file->extension();

            $info = $file->move(public_path($basePath),$fileName);
            // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg
            // 设置文件名称。
            $object = $basePath.'/'.$fileName;

            //$object = "uploads/testimage.jpg";
            // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
            $filePath = public_path().$object;

            $this->ossClient->uploadFile($this->bucket, $object, $filePath);

            // $fileInfo = $info->getFileInfo();

            //保存
            $model = UploadModel::create([
                'filename'=>$info->getFilename(),
                'origin_name'=>'',// $fileInfo['name'],//原本的名称 tp5能用的方法 tp暂时获取不到 后面再说
                'url'=>$this->urlHost.'/'.$object,
                'ext'=>$file->extension(),
                'type'=>$type,
                'size'=>$info->getSize()
            ]);

            //保存完毕后 删除掉主机上的文件
            @unlink($filePath);

            return $model;

        } catch(OssException $e) {
            throw new Exception($e->getTrace());
        }
    }


    public function images($type,$page,$pageSize){
        $start = ($page - 1) * $pageSize;
        $res = Db::table('upload')->where(['type'=>$type])->limit($start,$pageSize)->order('id desc')->select();
        $count = Db::table('upload')->where(['type'=>$type])->count();
        return ['data'=>$res,'total'=>$count];
    }

    /**
     * 删除图片
     * 图片路径
     * @param $object
     * @return boolean
     */
    public function delete($object){
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ossClient->deleteObject($this->bucket, $object);
        } catch(OssException $e) {
            return false;
        }
        return true;
    }

    public function uploadWordScreen($file,$videoId,$adminId,$type){
        //字幕文件不需要上传到阿里云吧
        $basePath = FileTool::createOssFilePath();
        $fileName = date("Ymd",time()).RandomTool::rand(10).".".$file->extension();
        $file->move(public_path($basePath),$fileName);
        $object = $basePath.'/'.$fileName;
        $filePath = public_path().$object;

//        //处理filePath 然后删掉filePath
        $wordList = Srt::parseSrt($filePath, $type);

        //如果已经存在该视频的字幕，则删除掉原来的字幕 重新插入
        $count = Db::table("video_wordscreen")->where(['video_id'=>$videoId])->count();
        if($count){
            //不删除，而是合并
            $this->uploadUpdateWordScreen($videoId,$adminId,$wordList);
            return;
            //Db::table('video_wordscreen')->where(['video_id'=>$videoId])->delete();
        }

        foreach( $wordList as $key => $val ) {
            $wordList[$key]['video_id'] = $videoId;
        }

        Db::table("video_wordscreen")->insertAll($wordList);
        $widthIds = Db::table("video_wordscreen")->where(['video_id'=>$videoId])->column("*","id");

        $videoWordScreenLog = [];
        $time = time();
        foreach( $widthIds as $key => $val ){
            array_push($videoWordScreenLog,[
                'video_id'=>$videoId,
                'wordscreen_id'=>$key,
                'content'=>serialize($val),
                'op_id'=>$adminId,
                'create_time'=>$time
            ]);
        }

        //为了记录是谁修改的
        //删掉之前的记录
        Db::table("video_wordscreen_log")->where(['video_id'=>$videoId])->delete();
        Db::table("video_wordscreen_log")->insertAll($videoWordScreenLog);

        //将视频状态改为正在编辑中
        Db::table("video_list")->where(['id'=>$videoId])->update([
            'wordscreen_editor'=>$adminId,
            'status'=>1 //正在编辑
        ]);
//        @unlink($filePath);

    }

    private function uploadUpdateWordScreen($videoId,$adminId,$wordList){
        $time = time();
        foreach( $wordList as $key => $val ){
            if(empty($val['en'])){
                unset($val['en']);
            }
            if(empty($val['cn'])){
                unset($val['cn']);
            }
            $wordscreen = Db::table('video_wordscreen')->where(['start'=>$val['start'],'video_id'=>$videoId])->find();
            if($wordscreen){
                Db::table("video_wordscreen")->where(['start'=>$val['start'],'video_id'=>$videoId])->update($val);
                Db::table("video_wordscreen_log")->insert([
                    'video_id'=>$videoId,
                    'wordscreen_id'=>$wordscreen['id'],
                    'content'=>serialize($val),
                    'op_id'=>$adminId,
                    'create_time'=>$time
                ]);
            }
        }
    }
}